package com.douxg.learning.tool.caffeine;

import com.github.benmanes.caffeine.cache.CacheLoader;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.LoadingCache;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Description
 * @Auther douxg
 * @Date 2021/3/22 10:53
 */
public class Test {
    public static volatile int initV = 0;
    public static LoadingCache<String, Integer> sysCfgCache = Caffeine.newBuilder()
            .maximumSize(5)
            .expireAfterWrite(20, TimeUnit.SECONDS)
            .refreshAfterWrite(2, TimeUnit.SECONDS)
            .build(new CacheLoader<String, Integer>() {
                @Nullable
                @Override
                public Integer load(@NonNull String key) throws Exception {
                    System.out.println("运行+++++++++++" + Thread.currentThread().getName());
                    initV++;
                    if (initV > 2) {
                        throw new Exception();
                    }
                    return initV;
                }
            });

    public static void main(String[] args) throws InterruptedException {
        Map<String, Integer> all = new HashMap<>();
        all.put("a", 1);
        all.put("b", 2);
        all.put("c", 3);
        all.put("a1", 3);
        all.put("a2", 3);
        all.put("a3", 6);
        sysCfgCache.putAll(all);
        for (int i = 0; i < 10; i++) {
//            System.out.println(sysCfgCache.get("a"));
//            System.out.println(sysCfgCache.get("b"));
//            System.out.println(sysCfgCache.getIfPresent("a"));
            System.out.println(sysCfgCache.get("a"));
//            System.out.println(sysCfgCache.get("a3"));
            TimeUnit.SECONDS.sleep(3);
        }
    }
}
